/**
 * Created by joustany on 16/11/2.
 */
ajaxComplete()
/**
 * 两数相加
 * @param arg1
 * @param arg2
 * @return {Number}
 */
$('.loding').show()
function accAdd(arg1, arg2) {
    // console.log(arg1, arg2, arg1 * 100 + arg2 * 100, (arg1 * 100 + arg2 * 100) / 100)
    return parseFloat((parseInt(arg1 * 1000) + parseInt(arg2 * 1000)) / 1000)
}

/**
 * 两数相减
 * @param arg1
 * @param arg2
 * @return {Number}
 */
function accSub(arg1, arg2) {
    return parseFloat((parseInt(arg1 * 1000) - parseInt(arg2 * 1000)) / 1000)
}

/**
 * 两数相乘
 * @param arg1
 * @param arg2
 * @return {Number}
 */
function accMul(arg1, arg2) {
    return parseFloat((parseInt(arg1 * 1000) * parseInt(arg2 * 1000)) / 1000000)
}

/**
 * find方法垫片
 */
if (!Array.prototype.find) {
    Object.defineProperty(Array.prototype, 'find', {
        value: function (predicate) {
            // 1. Let O be ? ToObject(this value).
            if (this == null) {
                throw new TypeError('"this" is null or not defined');
            }

            var o = Object(this);

            // 2. Let len be ? ToLength(? Get(O, "length")).
            var len = o.length >>> 0;

            // 3. If IsCallable(predicate) is false, throw a TypeError exception.
            if (typeof predicate !== 'function') {
                throw new TypeError('predicate must be a function');
            }

            // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
            var thisArg = arguments[1];

            // 5. Let k be 0.
            var k = 0;

            // 6. Repeat, while k < len
            while (k < len) {
                // a. Let Pk be ! ToString(k).
                // b. Let kValue be ? Get(O, Pk).
                // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
                // d. If testResult is true, return kValue.
                var kValue = o[k];
                if (predicate.call(thisArg, kValue, k, o)) {
                    return kValue;
                }
                // e. Increase k by 1.
                k++;
            }

            // 7. Return undefined.
            return undefined;
        }
    });
}

// 判断浏览器UA
var mobile = {
    getPlatform: function getPlatform() {
        var platform;
        if (mobile.b().android) {
            platform = 'android';
        } else if (mobile.b().ios || mobile.b().iPhone) {
            platform = 'ios';
        } else {
            platform = 'other';
            /*if (location.origin == 'http://test.aos.antfre.com:8858') {
             platform = other;
             } else {
             location.href = 'http://www.antfre.com/';
             }*/
        }
        return platform;
    },
    b: function browser() {
        var u = navigator.userAgent.toLowerCase();
        var app = navigator.appVersion.toLowerCase();
        return {
            txt: u, // 浏览器版本信息
            version: (u.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1], // 版本号
            msie: /msie/.test(u) && !/opera/.test(u), // IE内核
            mozilla: /mozilla/.test(u) && !/(compatible|webkit)/.test(u), // 火狐浏览器
            safari: /safari/.test(u) && !/chrome/.test(u), //是否为safair
            chrome: /chrome/.test(u), //是否为chrome
            opera: /opera/.test(u), //是否为oprea
            presto: u.indexOf('presto/') > -1, //opera内核
            webKit: u.indexOf('applewebkit/') > -1, //苹果、谷歌内核
            gecko: u.indexOf('gecko/') > -1 && u.indexOf('khtml') == -1, //火狐内核
            mobile: !!u.match(/applewebkit.*mobile.*/), //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( u;)? cpu.+mac os x/), //ios终端
            android: u.indexOf('android') > -1, //android终端
            iPhone: u.indexOf('iphone') > -1, //是否为iPhone
            iPad: u.indexOf('ipad') > -1, //是否iPad
            weixin: u.match(/MicroMessenger/i) == "micromessenger", //是否是微信内置
            webApp: !!u.match(/applewebkit.*mobile.*/) && u.indexOf('safari/') == -1 //是否web应该程序，没有头部与底部
        };
    }

};

/**
 * 修改页面title
 * @param title
 */
function modTitle(title) {
    $('.header_address .address').text(title);
    var device = window.sessionStorage.device
    // console.log(redirect.id)
    if (!device){
        window.sessionStorage.device = 1
        behavior.track('test',{
            "device_id": redirect.id,
            "device_name": title
        });
    }
    var mobile = navigator.userAgent.toLowerCase();
    if (/iphone|ipad|ipod/.test(mobile)) {
        var iframe = document.createElement('iframe');
        iframe.style.visibility = 'hidden';
        iframe.setAttribute('src', 'https://la-dev.oss-cn-hangzhou.aliyuncs.com/static/img/none.jpg');
        var iframeCallback = function() {
            setTimeout(function() {
                iframe.removeEventListener('load', iframeCallback);
                document.body.removeChild(iframe);
            }, 0);
        };
        iframe.addEventListener('load', iframeCallback);
        document.body.appendChild(iframe);
    }
}
// document.body.ontouchmove=function(e){
//     e.preventDefault();
// }
var data = {
    "banners": [
        {
            "title": "两岸咖啡百度百科介绍",
            "img": "https://la-dev.oss-cn-hangzhou.aliyuncs.com/backend/2017/05/10/5912a8a195b51.png",
            "url": "#shop#"
        },
        {
            "title": "智慧大厦店地图",
            "img": "https://la-dev.oss-cn-hangzhou.aliyuncs.com/backend/2017/05/10/5912a9f11d470.png",
            "url": "#shop#"
        },
        {
            "title": "猫屎咖啡",
            "img": "https://la-dev.oss-cn-hangzhou.aliyuncs.com/backend/2017/05/10/5912a9e60b8b2.png",
            "url": "#shop#"
        }
    ],
    "items": [
        {
            "id": "1",
            "item_id": "1",
            "name": "鱼排套餐",
            "price": "15.60",
            "promotion_price": "14.50",
            "img": "https://la-dev.oss-cn-hangzhou.aliyuncs.com/backend/2017/07/07/595f2bd1a857e.png",
            "tags": [
                {
                    "name": "好吃"
                },
                {
                    "name": "全家同款"
                }
            ],
            "img_small": "https://la-dev.oss-cn-hangzhou.aliyuncs.com/backend/2017/07/07/595f2bd1a857e.png"
        },
        {
            "id": "2",
            "item_id": "2",
            "name": "鱼排套餐",
            "price": "15.60",
            "promotion_price": "14.50",
            "img": "https://la-dev.oss-cn-hangzhou.aliyuncs.com/backend/2017/07/07/595f2bd1a857e.png",
            "tags": [
                {
                    "name": "好吃"
                },
                {
                    "name": "全家同款"
                }
            ],
            "img_small": "https://la-dev.oss-cn-hangzhou.aliyuncs.com/backend/2017/07/07/595f2bd1a857e.png"
        },
        {
            "id": "3",
            "item_id": "3",
            "name": "鱼排套餐",
            "price": "15.60",
            "promotion_price": "14.50",
            "img": "https://la-dev.oss-cn-hangzhou.aliyuncs.com/backend/2017/07/07/595f2bd1a857e.png",
            "tags": [
                {
                    "name": "好吃"
                },
                {
                    "name": "全家同款"
                }
            ],
            "img_small": "https://la-dev.oss-cn-hangzhou.aliyuncs.com/backend/2017/07/07/595f2bd1a857e.png"
        },
        {
            "id": "4",
            "item_id": "4",
            "name": "鱼排套餐",
            "price": "15.60",
            "promotion_price": "14.50",
            "img": "https://la-dev.oss-cn-hangzhou.aliyuncs.com/backend/2017/07/07/595f2bd1a857e.png",
            "tags": [
                {
                    "name": "好吃"
                },
                {
                    "name": "全家同款"
                }
            ],
            "img_small": "https://la-dev.oss-cn-hangzhou.aliyuncs.com/backend/2017/07/07/595f2bd1a857e.png"
        },
        {
            "id": "5",
            "item_id": "5",
            "name": "鱼排套餐",
            "price": "15.60",
            "promotion_price": "14.50",
            "img": "https://la-dev.oss-cn-hangzhou.aliyuncs.com/backend/2017/07/07/595f2bd1a857e.png",
            "tags": [
                {
                    "name": "好吃"
                },
                {
                    "name": "全家同款"
                }
            ],
            "img_small": "https://la-dev.oss-cn-hangzhou.aliyuncs.com/backend/2017/07/07/595f2bd1a857e.png"
        },
        {
            "id": "6",
            "item_id": "6",
            "name": "鱼排套餐",
            "price": "15.60",
            "promotion_price": "14.50",
            "img": "https://la-dev.oss-cn-hangzhou.aliyuncs.com/backend/2017/07/07/595f2bd1a857e.png",
            "tags": [
                {
                    "name": "好吃"
                },
                {
                    "name": "全家同款"
                }
            ],
            "img_small": "https://la-dev.oss-cn-hangzhou.aliyuncs.com/backend/2017/07/07/595f2bd1a857e.png"
        }
    ]
}

var page       = 0,
    source     = "android",
    version    = "2.3.0",
    able       = true,
    submitFlag = false,
    type       = false,
    foods      = new Array(), // 商品信息
    cart       = {}, // 购物车bus总线
    isSign     = window.localStorage.phone, //是否注册
    show_rule  = new Array(),//红包总金额
    show_type
var wx_link  = '',
    wx_title = '推荐有礼',
    wx_img   = 'https://la-pro.oss-cn-hangzhou.aliyuncs.com/logo/logo_120.jpg',
    wx_desc  = '发福利啦，快来领红包啦！';

$(function () {
    getShopView();
});

function res_success(res) {
    if (res.success) {
        return res.data
    } else {
        return false
    }
}

function res_fail(res, _redirect) {
    if (!res.success) {
        if (res.code === 401) {
            return false
        }
        showDialog(res.message)
        return res.message
    } else {
        return false
    }
}

/**
 * 获取店铺展示信息
 */
function getShopView() {
    var params = JSON.parse(window.localStorage.user);
    console.log(params)
	var openid = params.openid;
	var platform = mobile.b().weixin ? 'wechat' : '';
	if (params.platform === 'alipay') {
		platform = 'alipay';
	}else if(params.platform === 'dingTalk'){
		platform = 'dingTalk';
	}
    // if(!platform){
		// showDialog(0, 100, "您的打开方式不对！");
		// return false;
    // }
    var redirect = JSON.parse(decodeURIComponent(params['redirect']));
	console.log(redirect)
    var id = '';
    if (!params['redirect']) {
        showDialog(0, 300, "没有店铺id，请重新扫码");
        return false;
    } else {
        var userId = redirect.userId;
        // zhuge.identify(userId);
        // behavior.track('test',{
        //     "userId":userId,
        // })
        // console.log(userId)
        id = redirect.id;
        // zhuge.track('访问货架', {
        //     '货架编号': id,
        // });
    }
    urlRedirect(id);
    $.ajax({
        url: configApi('/shop/index'),
        data: {
            id: id || 2,
            access_token:redirect.token,
	        openid: openid || '',
	        platform: platform,
            access_token:redirect.token
        },
        dataType: 'json',
        type: "POST",
        timeout: 8000 //超时时间设置，单位毫秒
    }).done(function (res) {
        console.log(res)
        var data = res_success(res);
        if (data) {
            $.each(data.items,function (index,item) {
                $.each(item.items,function (index,item) {
                    foods.push(item)
                })
            })
            // console.log(data.is_sign)
            // if(data.show_sign == true){
            //     $('.packet—container').show()
            // }else {
            //     // $('.packet—container').show()
            //     $('.packet—container').hide()
            // }
            // data.show_type = 3
            // console.log(data.show_new_function)
            // data.show_new_function = 1
            // data.show_type = 1
            // data.show_new_function = 1
            show_type = data.show_type
            switch (show_type)
            {

                case 1:
                    $('.packet—container').show()//新人领取注册红包
                    break;
                case 2:
                    _hmt.push(['_trackEvent', "充值", "弹窗"]);
                    $('.topUp-container').show()//充值弹窗
                    document.addEventListener('touchmove', preHandler, false);
                    break;
                case 3:
                    $('.activity-container').show()//活动弹窗
                    break;
            }
            switch (data.show_new_function){//显示扫码指引层
                case 1:
                    $('.qrCode').show()
                    $('.packet—container').hide()
                    $('.topUp-container').hide()
                    $('.activity-container').hide()
                    break;
            }
            // console.log(data.is)
            modTitle(data.title);
            renderBanner(data.banners);
            renderFoods(data.items);
        } else {
            showDialog(0, 300, res.message);
        }
    }).fail(function () {
        showDialog(0, 300, "服务器异常,请退出重试");
    }).always(function (XMLHttpRequest, status) { //请求完成后最终执行参数
        if (status === 'timeout') {//超时,status还有success,error等值的情况
            // common.showDialog(0, 300, "网络请求超时,请重试!");
            setTimeout(function () {
                // common.showDialog(0, 300, "请稍候");
            }, 2000);
        }
    });

    //红包列表
    $.ajax({
        url: configApi('/user-coupon/index'),
        data: {
            access_token:redirect.token,
            pageSize:'20',
            usable:'1',
            is_index:'1',
        },
        dataType: 'json',
        type: "POST",
    }).done(function (res) {
        console.log(res)
        if (res.success){
            var hdata = res.data.list
            $.each(hdata,function (index,item) {
                show_rule.push(item)
            })
        }else {
            layer.open({
                content: res.message
                ,skin: 'msg'
                ,time: 2 //2秒后自动关闭
            });
        }
    }).fail(function () {
        layer.open({
            content: "服务器异常,请退出重试"
            ,skin: 'msg'
            ,time: 2 //2秒后自动关闭
        });
    })
}
/**
 * header
 * */
$('.header_balance').click(function () {
    "use strict"
    _hmt.push(['_trackEvent', "充值", "首页-Top-充值"]);
    setTimeout(function () {
        if (!isSign){
            window.location.href = './login.html'
        }else {
            window.location.href = './topUp.html'
        }
    },200)
})
$('.header_me').click(function () {
    $('.loding').show()
    if(!isSign){
        window.location.href = './login.html?record=me'
        $('.loding').hide()
    }else {
        window.location.href = './me.html'
        $('.loding').hide()
    }
})
$('.qrCode,.qrCode_layer').click(function () {
    $('.qrCode').hide()
    showType()
    document.removeEventListener('touchmove', preHandler, false)
})
$('.header_code').click(function () {
    "use strict"
    $('.loding').show()
    // console.log(redirect)
    // var result = 'result,6903757998023'
    // qrCode(result)
    if(params.platform == 'wechat'){
        $('.loding').hide()
        wx.ready(function () {
            // 9.1.2 扫描二维码并返回结果
            wx.scanQRCode({
                needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                success: function (res) {
                    var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                    qrCode(result)
                },
            });
        })
        wx.error(function () {
            layer.open({
                content: '签名无效,请刷新页面'
                ,skin: 'msg'
                ,time: 2 //2秒后自动关闭
            });
        })
    }else {
        $('.loding').hide()
        ap.scan({
            type: 'bar'
        }, function(res){
            // ap.alert(res.code);
            qrCode(res.code)
        });
    }
    console.log($(this).attr('id'))
    // qrCode('asddas,6903757998023')
})
function qrCode(result) {
    if(params.platform == 'wechat'){
        var code = result.split(',')[1]
        if (isNaN(code)){
            layer.open({
                content: "请用手遮挡二维码"
                ,skin: 'msg'
                ,time: 2 //2秒后自动关闭
            });
            return
        }
    }else {
        var code = result
    }
    $.ajax({
        url: configApi('/device-item/find-by-code'),
        data:{
            id:redirect.id,
            code:code
        },
        dataType: 'json',
        type:'get',
    }).done(function (res) {
        console.log(res)
        if (res.success){
            var itemId = res.data.itemId,
                docItem = $('.food-item')
            $.each(docItem,function (i,item) {
                if(itemId == $(this).data().id){
                    $('#food-right').find('h3').css({'position': 'static'})
                    $("#food-right").scrollTop(0).animate({scrollTop: $(this).offset().top-$('.header').height()},0)
                    var index = $(this).parents('.classifg').index()-1
                    $('.type-style').eq(index).addClass('food-type_list').siblings().removeClass('food-type_list')
                    $(this).find('.add_icon').click()
                    // console.log($(this).parents('.classifg').index()-1)
                    return false
                }
            })
        }else {
            layer.open({
                content: res.message
                ,btn: '确定'
            });
        }
    }).fail(function () {
        layer.open({
            content: "服务器异常,请退出重试"
            ,skin: 'msg'
            ,time: 2 //2秒后自动关闭
        });
    })
}
function showType() {
    setTimeout(function () {
        if(show_type == 1){
            $('.packet—container').show()
        }
        show_type = ''
    },500)
}
/**
 * 充值层按钮
 * */
$('.topUp—submit').click(function () {
// console.log(redirect.phone = '')
    _hmt.push(['_trackEvent', "充值", "首页-T-充值","","1000"]);
    // window.location.href = './topUp.html'
    setTimeout(function () {
        if (!isSign){
            window.location.href = './login.html?'
        }else {
            window.location.href = './goodsDesc.html'
        }
    },200)
})

/**
 * 充值弹出层
 * */
$('.activity-close').click(function () {
    $('.activity-container').hide()
    document.removeEventListener('touchmove', preHandler, false)
})
$('.topUp_close').click(function () {
    $('.topUp-container').hide()
    document.removeEventListener('touchmove', preHandler, false)
})
$('.activity—btn').click(function () {
    window.location.href = 'https://m.antfre.com/webApp/shareParams.html?lineLink=http://api.antfre.com/h5/share?share_id=M8TaE6xbM5D5Ib59'
})



/**
 * 将分享出去的店铺进行重定向
 */
function urlRedirect(shopId) {
    if (window.location.href.indexOf('from=') > -1) {
        window.location.href = configApi('/h5/index') + '?id=' + shopId;
    }
}
/**
 * 红包部分-注册
 * */
$(document).on('click','.paket_close,.packe_mask',function () {
    "use strict"
    $('.packet—container').fadeOut('fast');
})
var count = 60;
var InterValObj
var params = JSON.parse(window.localStorage.user);
var redirect = JSON.parse(decodeURIComponent(params['redirect']));
$(document).on('click','.obtain',function () {
    "use strict"
    // console.log(redirect.token)
    var access_token = redirect.token
    var phone = $(".phone")[0].value
    var phoneVerifg = /^1[34578]\d{9}$/;
    if(!phoneVerifg.test($(".phone")[0].value))
    {
        showDialog(0, 200, "请输入有效的手机号码!")
    }else {
        $.ajax({
            url: configApi('/sms/send'),
            data: {
                phone:phone,
                type: 'region',
                access_token: access_token
            },
            dataType: 'json',
            type: "POST",
        }).done(function (res) {
                // alert(res.message)
                if (res.success){
                    $('.packet_put').focus()
                    $('.obtain').addClass('disabled')//通过class切换禁止点击事件
                    $(".obtain").removeClass('obtain');
                    $(".obtain").html(count + "秒后重试");
                    InterValObj = window.setInterval(SetRemainTime, 1000)
                    showDialog(0, 200, res.message)
                }else {
                    showDialog(0, 200, res.message)
                }
        }).fail(function () {
                showDialog(0, 200, "服务器异常,请退出重试")
        })
    }
})
//倒计时
function SetRemainTime() {
    console.log(count)
    if (count == 0) {
        window.clearInterval(InterValObj);//停止计时器
        $(".disabled").addClass('obtain');
        $(".obtain").removeClass("disabled");//启用按钮
        $(".obtain").html("获取验证码");
        count = 60
    }
    else {
        count--;
        $(".disabled").html(count + "秒后重试");
    }
}
$(document).on('click','.packet_led',function () {
    $('.loding').show()
    var phone = $(".phone")[0].value
    var code = $(".packet_put")[0].value
    if(code.length == 4){
        $.ajax({
            url: configApi('/user/region'),
            data: {
                phone:phone,
                code: code,
                access_token: redirect.token
            },
            dataType: 'json',
            type: "POST",
        }).done(function (res) {
                console.log(res)
                $('.loding').hide()
            if (res.success){
                if (res.code == 1001){
                    window.clearInterval(InterValObj)
                    isSign = true
                    showDialog(0, 200, res.message)
                    $('.packet—container').fadeOut('fast');
                }else {
                    getSucceed(res.data)
                    window.clearInterval(InterValObj)
                    $('.packet—container').fadeOut('fast');
                    isSign = true
                    $('.packet—succe-container').fadeIn();
                }
            }else {
                showDialog(0, 200, res.message)
            }
        }).fail(function () {
            showDialog(0, 200, "服务器异常,请退出重试")
        })
    }else {
        $('.loding').hide()
        showDialog(0, 200, "您输入的验证码有误!")
    }
})
//获取红包
function getSucceed(user) {
    console.log(user)
    $('.succe_num').text(user.money)
    $('.succe_xin').text(user.title)
}
/**
 * 红包部分-成功
 * */
$(document).on('click','.packet—succe_mask,.succe_close',function () {
    "use strict"
    $('.packet—succe-container').fadeOut('fast');
})
/**
 * 渲染banner
 * @param banners
 */
function renderBanner(banners) {
    "use strict"
    console.log(banners)
    // console.log(redirect)
    // if (banners.length === 1){
    //     $('.swiper-pagination').remove()
    // }
    var html = ''
    $.each(banners,function (i,item) {
        console.log(item.url)
        html +='<div class="swiper-slide" id="'+ item.id +'" data-str="'+ item.type_str +'" data-title="'+ item.title +'" data-url="'+ item.url +'"> ' +
            '<a class="banner-link" href="javascript:"> ' +
            '<img class="banner" src="'+ item.img +'"> ' +
            '</a> ' +
            '</div>'
    })
    $('.swiper-wrapper').html(html)
    // $('.swiper-container').push('<div class="swiper-pagination"></div>')
    var mySwiper = new Swiper('.banner-container', {
        // speed:2000,
        loop : true,
        autoplay: {
            delay: 3000,
            disableOnInteraction: false,
        },//可选选项，自动滑动
        pagination: {
            el: '.swiper-pagination',
            bulletElement : 'li',
        },
    })
    if (banners.length === 1){
        $('.swiper-pagination').remove()
        mySwiper.destroy(false)
    }
    $('.swiper-slide').click(function () {
        // console.log($(this).attr('data-title'))
        var _this = $(this)
        var banner_name = _this.attr('data-title'),
            type_str = _this.attr('data-str'),
            banner_id = _this.attr('id')
        // var banner_url = $(this).attr('data-url')
        // console.log(banner_url)
        _hmt.push(['_trackEvent', "banner",type_str,banner_id,]);
        behavior.track("点击banner",{
                            'bannerName':banner_name,
                            'userId':redirect.userId
                        })
        setTimeout(function () {
            window.location.href = _this.attr('data-url')
        },200)
        // $(this).find('.banner-link').attr("href",$(this).attr('data-url'))
    })
    // $('.banner').attr('src', banners[0].img);
    // if (banners[0].url) {
    //     $('.banner-container').click(function () {
    //         _hmt.push(['_trackEvent', "充值", "banner"]);
    //         setTimeout(function () {
    //             behavior.track("点击banner",{
    //                 'bannerName':banners[0].title,
    //                 'userId':redirect.userId
    //             })
    //             window.location.href = banners[0].url
    //         },200)
    //     });
    // }
}

/**
 * 渲染商品
 * @param foods
 */
function renderTopFoods(foods){
    "use strict"
    var html = ''
    $.each(foods,function (i,item) {
        $.each(item,function (index,item) {
            var cart_num = item.num
            var cart_pricepa = item.promotion_price
            html += '<div class="cart-layout_topDetails" data-id="' + item.id + '">'
            html += '<div class="cart-layout_topfoods">' + item.name + ' </div>'
            html += '<div class="cart-layout_topPrice">￥<span class="">' + accMul(cart_num, cart_pricepa) +'</span></div>'
            html += '<div class="cart-layout_topRigth">'
            html += '<span class="cart-layout_topReduceIcon" onclick="">'
            html += '<img src="./images/ui_icon/icon_jian.png" alt="">'
            html += '</span>'
            html += '<span class="cart_topNum">' + cart_num +'</span>'
            html += '<span class="cart-layout_topAddIcon" onclick="">'
            html += '<img src="./images/ui_icon/icon_add.png" alt="">'
            html += '</span>'
            html += '</div>'
            html += '</div>'
        })
        $('.cart-layout_topDe').html(html)
    })
}
var leftList = false
function renderFoods(foods) {
    "use strict"
    console.log(foods)
    var products = foods;
    var html = '';
    var htmlifg = ''
    $.each(products, function (index,classifg) {
        // console.log(classifg)
        if(index === 0){
            htmlifg += '<li class="type-style food-type_list" onclick="" data-index="'+classifg.id+'">'
            htmlifg += '<h1>'+classifg.show_title+'</h1>'
            htmlifg += '</li>'
        }else {
            htmlifg += '<li class="type-style" onclick="" data-index="'+classifg.id+'">'
            htmlifg += '<h1>'+classifg.show_title+'</h1>'
            htmlifg += '</li>'
        }
        html += '<div class="classifg" data-index="'+classifg.id+'">'
        html += '<div class="classifg_title">'
        html += '<h3 class="classifg_title">'+classifg.show_title+'</h3>'
        html += '</div>'
        html += '<div class="food-classifg">'
        $.each(classifg.items,function (index,item) {
            html += '<li class="food-item food-box" data-id="' + item.id + '">';
            html += '<img class="food-image" src="' + item.img_small + '" alt="">';
            html += '<div class="food-news">'
            html += '<div class="name ellipsis"><h1>' + item.name + '</h1></div>';
            html += '<div class="tag-list">';
            if (item.tags.length !== 0) {
                $.each(item.tags, function (i, tag) {
                    html += '<span class="tag-item">' + tag.name + '</span>';
                });
            } else {
                html += '<span class="tag-item tag-blank">' + '无' + '</span>';
            }
            html += '</div>';
            html += '<div class="buy-info">';
            html += '<section class="food-price">';
            html += '<div class="sales-price">';
            html += '<span class="small">¥</span><span>' + item.promotion_price + '</span>';
            html += '</div>';
            if (item.price > 0) {
                html += '<div class="original-price">';
                html += '<span class="small">¥</span><span>' + item.price + '</span>';
                html += '</div>';
            }
            html += '</section>';
            html += '<section class="cart_module">';
            html += '<section class="cart_button">';
            html += '<span class="reduce_icon">';
            html += '<img src="./images/ui_icon/icon_jian.png" alt="">';
            html += '</span>';
            html += '<span class="cart_num">0</span>';
            html += '<span class="add_icon">';
            html += '<img src="./images/ui_icon/icon_add.png" alt="">';
            html += '</span>';
            html += '</section>';
            html += '</section>';
            html += '</div>';
            html += '</div>'
            html += '</li>';
        })
        html += '</div>'
        html += '</div>'
    });
    $('.food-list_content').append(html);
    $('.food-type').html(htmlifg)
    setTimeout(function () {
        $('.container').fadeIn(100);
    }, 200);
    //购物车本地存储
    var sessCart = JSON.parse(sessionStorage.getItem('cart'))
    console.log(sessCart)
    if(sessCart){
        totalCartInfo(sessCart)
        $.each($('.food-item'),function (i,item) {
            var docItem = $(this),
                docItemId = docItem.data('id')
            $.each(sessCart,function (i,item) {
                console.log(docItemId)
                cart[item.id] = {
                    'num': item.num,
                    'id': item.id,
                    'name': item.name,
                    'price': item.price,
                    'promotion_price': item.promotion_price,
                    'discount_type': item.discount_type,
                    'discount_price': item.discount_price,
                    'category_id': item.category_id,
                    'group_category_id': item.group_category_id || '',
                    'discount_num': 0
                };
                var itemId = item.id
                if(itemId == docItemId){
                    docItem.find('.cart_num').text(item.num).show()
                    docItem.find('.reduce_icon').show()
                    // return
                }
                // console.log(itemId,docItem)
            })
        })
    }
    console.log(cart)
    // console.log($('.add_icon').parents(""))
    $.each($('.add_icon'),function (index,item) {
        var add_icon =  $(this),
            yearId = $(this).parents(".food-item").attr("data-id"),
            localYaer = window.sessionStorage.yearId
        // console.log(JSON.parse(window.sessionStorage.year)[localYaer])
        if (localYaer){
            if(yearId === localYaer){
                // console.log(add_icon.parents('.classifg').index())
                var yearIndex = add_icon.parents('.classifg').index()-1
                $('.type-style').eq(yearIndex).addClass('food-type_list').siblings().removeClass('food-type_list')
                console.log($('.type-style').eq(yearIndex))
                $('.food-type').scrollTop(0).animate({scrollTop:$('.type-style').eq(yearIndex)})
                // alert($(this).parents('.food-item').attr('data-id'))
                // console.log($(this).parents('.food-item'))
                // $("#food-right").scrollTop($(this).offset().top)
                // $(this).click()

                $("#food-right").scrollTop(0).animate({scrollTop: $(this).parents('.food-item').offset().top-40},1000,function () {
                   // add_icon.click()
                });
                // setTimeout(function () {
                //     $(this).click()
                // },200)
                // return
            }
        }
    })
    // var waypoint = new Waypoint({
    //     element: document.querySelector('.classifg'),
    //     handler: function(direction) {
    //         // notify('I am enabled')
    //         console.log('aa')
    //     },
    //     offset: ''
    // })

    $('.food-list').on('touchmove',function (e) {
        e.stopPropagation();
        leftList = false
        // console.log(params.platform)
        $('.classifg').waypoint(function (e, direction) {
            if (leftList){
                return
            }
            $('.banner-container').show()
            // e.stopPropagation()
            var $active = $(this);
            var i = $active.index() - 1
            // console.log(direction)
            // $('.type-style')
            $('.type-style').removeClass('food-type_list').eq(i).addClass('food-type_list');
            if (params.platform == 'wechat'){
                if (direction == 'down') {
                    $(this).find('h3').css({'position': 'fixed', 'top': '6.672%'})
                } else {
                    $(this).find('h3').css({'position': 'static'})
                }
            }
        }, {
            // offset: 18,
            context: '#food-right'
        });
    })
}
/**
 * 分类列表联动
 * */
//左侧点击滚动
$(document).on('click','.type-style',function (e) {
    // $(".food-list").animate({scrollTop:123})
    leftList = true
    if ($(this).index()== 0){
        $('.banner-container').show()
    }else {
        $('.banner-container').hide()
    }

    // $('.banner-container').hide()
    $('.classifg h3').css("position","relative")
    // $('.food-list_content').addClass('food-list_con')
    // $('.food-list').unbind ('scroll');
    var id = $(this).data('index')
    var scHeight = 0;
    var top = 0
    // console.log(id)
    for(var i = 0; i<$('.classifg').length;i++){
        if(id == $('.classifg')[i].getAttribute('data-index')){
            // console.log($('.classifg')[i].getAttribute('data-index'))
            for( var j = 0;j<i;j++){
                scHeight  += $('.classifg')[j].scrollHeight;
                top += $('.classifg').eq(i).position().top;
                // console.log($('.classifg').eq(i).position().top)
            }
            $('.type-style').eq(i).addClass('food-type_list').siblings().removeClass('food-type_list')
            $(".food-list").animate({scrollTop:scHeight})
            var contentH = $('.food-list').height(), //内容高度
                viewH = $('.food-list').height(),//可见高度
                scrollTop = $('.food-list').scrollTop()//滚动高度
            if(scrollTop/(contentH -viewH)>=0.95){
                var oo = $(this).parent();
                var cc = oo.children();
                for(var xx = 0; xx<cc.length;xx++ ){
                    $(this).addClass('food-type_list')
                    cc[xx].classList.remove('food-type_list')
                }
                $(this).addClass('food-type_list');
            }
        }

    }
})
function getFoodInfo(dom) {
    var food_id = parseInt(dom.parents('.food-item').attr('data-id'));
    // console.log(food_id)
    var food = foods.find(function (item) {
        return parseInt(item.id) === food_id;
    });
    // console.log(food)
    var reduce_icon = dom.children('.reduce_icon'),
        cart_num    = dom.children('.cart_num'),
        add_icon    = dom.children('.add_icon');
    return {
        "food": food,
        "reduce_icon": reduce_icon,
        "cart_num": cart_num,
        "add_icon": add_icon,
        "food_id":food_id
    }
}
function cartFoodInfo(dom) {
    var food_id = parseInt(dom.parents('.cart-layout_topDetails').attr('data-id'));
    console.log(food_id)
    var food = foods.find(function (item) {
        return parseInt(item.id) === food_id;
    });
    // console.log(food)
    var reduce_icon = dom.children('.reduce_icon'),
        cart_num    = dom.children('.cart_num'),
        add_icon    = dom.children('.add_icon');
    return {
        "food": food,
        "reduce_icon": reduce_icon,
        "cart_num": cart_num,
        "add_icon": add_icon,
        "food_id":food_id
    }
}
/**
 * cart-top 添加删除商品联动
 */
$(document).on('click','.cart-layout_topAddIcon',function () {
    "use strict"
    // console.log($(this).parents('.cart-layout_topRigth'))
    var button_box = $(this).parents('.cart-layout_topRigth');
    var _food_attr = cartFoodInfo(button_box);
    var food        = _food_attr.food,
        cart_num    = _food_attr.cart_num,
        reduce_icon = _food_attr.reduce_icon;
    if (cart[food.id]) {
        cart[food.id]['num']++;
        // cart_num.text(cart[food.id]['num']);
    } else {
        cart[food.id] = {
            'num': 1,
            'id': food.id,
            'name': food.name,
            'price': food.price,
            'promotion_price': food.promotion_price,
            'discount_type': food.discount_type,
            'discount_price': food.discount_price,
            'category_id': food.category_id,
            'group_category_id': food.group_category_id || '',
            'discount_num': 0
        };
        // reduce_icon.show();
        // cart_num.show().text('1');
    }
    $.each($('.food-item'),function (index,item) {
        // console.log($(this).data('id'))
        // console.log(_food_attr.food_id,$(this).data('id'))
        if (_food_attr.food_id == $(this).data('id')){
            // console.log($(this).find('.cart_num'))
            $(this).find('.cart_num').show().text(cart[food.id]['num'])
            $(this).find('.reduce_icon').show()
            // cart_num.text(cart[food.id]['num']);
        }
    })
    // console.log(cart)
    totalCartInfo(cart);
    // console.log(food)
});
$(document).on('click', '.cart-layout_topReduceIcon', function () {
    "use strict"
    var button_box = $(this).parents('.cart-layout_topRigth');
    var _food_attr = cartFoodInfo(button_box);
    var food        = _food_attr.food,
        cart_num    = _food_attr.cart_num,
        reduce_icon = _food_attr.reduce_icon;
    if (cart[food.id]['num'] > 1 && cart) {
        cart[food.id]['num']--;
        // cart_num.text(cart[food.id]['num']);
    } else {
        delete cart[food.id];
        reduce_icon.hide();
        cart_num.hide().text('0');
        localClear()
    }
    $.each($('.food-item'),function (index,item) {
        // console.log($(this).data('id'))
        // console.log(_food_attr.food_id,$(this).data('id'))
        if (_food_attr.food_id == $(this).data('id')){
            // console.log($(this).find('.cart_num'))
            if (cart[food.id]){
                $(this).find('.cart_num').text(cart[food.id]['num'])
            }else {
                $(this).find('.cart_num').hide().text('0')
                $(this).find('.reduce_icon').hide()
            }
        }
    })
    userBehavior(false,food)
    totalCartInfo(cart);

});
/**
 *  清空购物车
 */

$(document).on('click','.cart-layout_topClear',function () {
    "use strict"
    cart= {}
    totalCartInfo(cart)
    $('.reduce_icon').hide()
    $('.cart_num').hide().text('0')
    localClear()
})
/**
 * 显示隐藏购物车top详情
 */
// console.log($('.selected').setAttribute(""))
$(document).on('click','.selected',function () {
    "use strict"
    if($('.total-price').text() == 0){
        $(".cart-layout_top").css('display','none');
        showDialog(0, 300, "您还未选购商品");
    }else {
         // $('.cart-layout_top').fadeIn()
         // $('.cart-layout_top').css({"top":"initial","display": "block"},5000)
        $(".cart-layout_topTow").animate({bottom:"0"});
        $(".cart-layout_top").show();
        $('.selected').attr("class","selecteds")
    }
})
$(document).on('click','.selecteds,.cart-layout_topOne',function () {
    $(".cart-layout_topTow").animate({bottom:"-100%"});
    $('.cart-layout_top').fadeOut()
    $('.selecteds').attr("class","selected")
})

/**
 * 添加商品
 */
function animation($that) {
    var cart = $('.cart-layout_logo');
    // console.log($that.parents('.food-item').find("img"))
    var imgtodrag = $that.parents('.food-item').find("img").eq(0);
    if (imgtodrag) {
        var imgclone = imgtodrag.clone()
            .offset({
                top: imgtodrag.offset().top,
                left: imgtodrag.offset().left
            })
            .css({
                'position': 'absolute',
                'z-index': '100',
                'border-radius':'50%'
            })
            .appendTo($('body'))
            .animate({
                'top': cart.offset().top + 10,
                'left': cart.offset().left + 10,
                'width':22,
                'height': 22
            }, 600);

        imgclone.animate({
            'width': 0,
            'height': 0
        }, 0,function () {
            $(this).detach()
        });
    }
}
function userBehavior(add,food) {
    if(add){
        behavior.track("产品选择",{
            "goodsName":food.name
        })
    }else {
        behavior.track("产品取消",{
            'goodsName':food.name
        })
    }
}
$(document).on('click', '.food-list .add_icon', function () {
    "use strict"
    var button_box = $(this).parents('.cart_button');
    var _food_attr = getFoodInfo(button_box);
    var food        = _food_attr.food,
        cart_num    = _food_attr.cart_num,
        reduce_icon = _food_attr.reduce_icon;
    goodsType(food.type)
    if (type){
        return
    }
    animation($(this))
    if (cart[food.id]) {
        cart[food.id]['num']++;
        // cart_num.text(cart[food.id]['num']);
    } else {
        cart[food.id] = {
            'num': 1,
            'id': food.id,
            'name': food.name,
            'price': food.price,
            'promotion_price': food.promotion_price,
            'discount_type': food.discount_type,
            'discount_price': food.discount_price,
            'category_id': food.category_id,
            'group_category_id': food.group_category_id || '',
            'discount_num': 0,
            'type':food.type,
        };
        // reduce_icon.show();
        // cart_num.show().text('1');
    }
    $.each($('.food-item'),function (index,item) {
        // console.log($(this).data('id'))
        // console.log(_food_attr.food_id,$(this).data('id'))
        if (_food_attr.food_id == $(this).data('id')){
            // console.log($(this).find('.cart_num'))
            $(this).find('.cart_num').show().text(cart[food.id]['num'])
            $(this).find('.reduce_icon').show()
            // cart_num.text(cart[food.id]['num']);
        }
    })
    userBehavior(true,food)
    // behavior.track("产品选择",{
    //     "goodsName":food.name
    // })
    // zhuge.track('产品选择', {
    //     '商品名称': food.name,
    // });
    // console.log(cart)
    totalCartInfo(cart);

});
function goodsType(foodType) {
    // console.log(foodType)
    if($.isEmptyObject(cart)){
        type = false
    }else {
        if (foodType == 2){
            $.each(cart, function (i, item) {
                "use strict"
                // console.log(item)
                if (item.type === '1'){
                    type = true
                    showDialog(0, 300, '现售商品 和 年货礼包 不能同时下单!')
                    return
                }else {
                    type = false
                }
            })
        }else if(foodType == 1){
            $.each(cart, function (i, item) {
                "use strict"
                if (item.type === '2'){
                    type = true
                    showDialog(0, 300, '现售商品 和 年货礼包 不能同时下单!')
                    return
                }else {
                    type = false
                }
            })
        }
    }
}

/**
 * 移除商品
 */
function localClear() {
    window.sessionStorage.removeItem('yearId')
}
$(document).on('click', '.food-list .reduce_icon', function () {
    "use strict"
    var button_box = $(this).parents('.cart_button');
    var _food_attr = getFoodInfo(button_box);
    var food        = _food_attr.food,
        cart_num    = _food_attr.cart_num,
        reduce_icon = _food_attr.reduce_icon;
    console.log(food.id)
    if (cart[food.id]['num'] > 1 && cart) {
        cart[food.id]['num']--;
        // cart_num.text(cart[food.id]['num']);
    } else {
        type = false
        delete cart[food.id];
        reduce_icon.hide();
        cart_num.hide().text('0');
        localClear()
    }
    $.each($('.food-item'),function (index,item) {
        // console.log($(this).data('id'))
        // console.log(_food_attr.food_id,$(this).data('id'))
        if (_food_attr.food_id == $(this).data('id')){
            // console.log($(this).find('.cart_num'))
            if (cart[food.id]){
                $(this).find('.cart_num').text(cart[food.id]['num'])
            }else {
                $(this).find('.cart_num').hide().text('0')
                $(this).find('.reduce_icon').hide()
            }
        }
    })
    userBehavior(false,food)
    totalCartInfo(cart);
});

/**
 * 购物车信息
 * @param cartList
 */
function totalCartInfo(cartList) {
    var foods = [];
    var cart_container = $('.cart-container');
    var total_num   = 0,
        total_price = 0;
    var group_category_ids = [];
    var discountFlag = {};
    sessionStorage.setItem("cart", JSON.stringify(cartList));
    if (!$.isEmptyObject(cartList)) {
        $.each(cartList, function (i, item) {
            // console.log(item)
            total_num += parseInt(item.num);
            if (item.group_category_id) {
                group_category_ids.push(parseInt(item.group_category_id));
            }
        });
        $.each(cartList, function (i, item) {
            if (group_category_ids.indexOf(parseInt(item.category_id)) > -1) {
                if (discountFlag[item.category_id]) {
                    discountFlag[item.category_id] += item.num;
                } else {
                    discountFlag[item.category_id] = item.num;
                }
            } else {
                discountFlag[item.category_id] = 0;
            }
        });
        // console.log(discountFlag);
        $.each(cartList, function (i, item) {
            if (item.discount_type === '1') {
                // todo 首份折扣
                total_price = accAdd(total_price, accMul(item.promotion_price, item.num));
            } else if (item.discount_type === '2' && discountFlag[item.group_category_id]) {
                var min = Math.min(item.num, discountFlag[item.group_category_id]);
                var max = Math.max(item.num, discountFlag[item.group_category_id]);
                total_price = accAdd(total_price, accMul(item.discount_price, min));
                if (item.num > min) {
                    console.log('原价个数：' + (item.num - min));
                    total_price = accAdd(total_price, accMul(item.promotion_price, item.num - min));
                }
            } else {
                total_price = accAdd(total_price, accMul(item.promotion_price, item.num));
            }
        });
        //红包降序
        show_rule.sort(function(a, b){
            console.log(a.num)
            if (a.money === b.money) {
                return new Date(b.money_limit.replace(/-/g, "/")) - new Date(a.money_limit.replace(/-/g, "/"))
            } else {
                return a.money - b.money;
            }
        });
        // 限制金额升序
        show_rule.sort(function (a,b) {
            return a.money_limit-b.money_limit
        })
        //遍历数组显示红包金额
        $.each(show_rule,function (i,item) {
            // console.log(item.money_limit)
            // console.log(total_price < item.money_limit)
            if (total_price < item.money_limit){
                $('.full-sub').show().html('还差'+ accSub(item.money_limit,total_price) +'元可使用' + '<span style="color: #FF5436;font-family: inherit">'+ item.money +'元' + '</span>' + '红包')
                return false
            }else {
                $('.full-sub').show().html('下单可使用' + '<span style="color: #FF5436;font-family: inherit">'+ item.money +'元' + '</span>' + '红包')
            }
        })

        $('.selected-num').text(total_num);
        $('.selected-numOne').text(total_num)
        $('.total-price').text(total_price);
        $('.cart-layout_logo img')[0].src = './images/ui_icon/icon_已购.png'
        $('.cart-price').addClass('cart-price_types')
        $('.submit-btn-red').addClass('submit-btn-red_types')
        $('.submit-btn-red').attr('disabled',"true");
        foods.push(cartList)
        renderTopFoods(foods)
        $('.selected-num').css('display','block')
        // console.log(foods)
        // cart_container.slideDown();
    } else {
        $('.full-sub').hide()
        // cart_container.slideUp();
        $('.cart-layout_logo img')[0].src = './images/ui_icon/icon_购买.png'
        $('.cart-price').removeClass("cart-price_types")
        $('.submit-btn-red').removeClass('submit-btn-red_types')
        $('.cart-layout_top').fadeOut()
        $('.selected').show(500)
        $('.total-price').text('0');
        $('.selected-num').css('display','none')
        // $('.cart-price').animate({marginLeft:'5.125rem'})
    }
}

/**
 * 禁用ios弹性效果
 * @param e
 */
var preHandler = function(e){e.preventDefault();}

/**
 * 显示商品详情
 */
$(document).on('click', '.food-image', function () {
    "use strict"

    $('.container').css('overflow-y', 'hidden');
    document.addEventListener('touchmove', preHandler, false);
    var food_item = $(this).parents('.food-item');
    var food_id = parseInt(food_item.attr('data-id'));
    var food = foods.find(function (item) {
        return parseInt(item.id) === food_id;
    });
    behavior.track("查看详情",{
        "goodsName":food.name
    })
    // zhuge.track('查看详情', {
    //     '商品名称': food.name,
    // });
    var food_num = parseInt(food_item.find('.cart_num').text());
    var food_detail_box = $('.food-detail-container');
    var tag_html = '';
    if (food_num > 0) {
        food_detail_box.find('.reduce_icon').show();
        food_detail_box.find('.cart_num').show().text(food_num);
        food_detail_box.find('.cart_tow').show()
        food_detail_box.find('.cart_one').hide()
    } else {
        food_detail_box.find('.reduce_icon').show();
        food_detail_box.find('.cart_num').show().text('0');
        // console.log(food_detail_box.find('.reduce_icon'))
        // console.log(food_detail_box.find('.cart_tow'))
        food_detail_box.find('.cart_tow').hide()
        food_detail_box.find('.cart_one').show()

    }
    food_detail_box.find('.food-image_popup').attr('src', food.img);
    food_detail_box.find('.name').text(food.name);
    if (food.desc) {
        food_detail_box.find('.food-desc-box').show();
        food_detail_box.find('.food-desc').text(food.desc);
    } else {
        food_detail_box.find('.food-desc-box').hide();
    }
    $.each(food.tags, function (i, item) {
        tag_html += '<span class="tag-item">' + item.name + '</span>';
    });
    food_detail_box.find('.tag-list').html(tag_html);
    if (food.promotion_price) {
        $('#sales-price').text(food.promotion_price);
    } else {
        $('.sales-price').hide();
    }
    if (food.price) {
        $('#original-price').text(food.price);
    } else {
        $('.original-price').hide();
    }
    console.log(food.has_details)
    if(food.has_details === '0'){
        $('.food-detail-layout.food-item').attr('data-id', food_id);
        setTimeout(function () {
            $('.container').addClass('filter');
        }, 50);
        food_detail_box.fadeIn(100);
    }else {
        console.log(cart)
        window.sessionStorage.year = JSON.stringify(cart)
        window.location.href = './yearGoods.html?year='+ food.id +''
    }
});

/**
 * 添加商品和移除商品联动
 */


$(document).on('click','.cart_one',function () {
    "use strict"
    var button_box = $(this).parents('.cart_module');
    // console.log($(this).parents('.cart_button'))
    console.log(button_box)
    var _food_attr = getFoodInfo(button_box);
    var food        = _food_attr.food,
        cart_num    = _food_attr.cart_num,
        reduce_icon = _food_attr.reduce_icon;
    goodsType(food.type)
    if (type){
        return
    }
    if (!cart[food.id]) {
        cart[food.id] = {
            'num': 1,
            'id': food.id,
            'name': food.name,
            'price': food.price,
            'promotion_price': food.promotion_price,
            'discount_type': food.discount_type,
            'discount_price': food.discount_price,
            'category_id': food.category_id,
            'group_category_id': food.group_category_id || '',
            'discount_num': 0
        };
    }
    // console.log(cart)
    $.each($('.food-item'),function (index,item) {
        // console.log($(this).data('id'))
        // console.log(_food_attr.food_id,$(this).data('id'))
        if (_food_attr.food_id == $(this).data('id')){
            // console.log($(this).find('.cart_num'))
            $(this).find('.cart_num').show().text('1')
            $(this).find('.reduce_icon').show()
            // cart_num.text(cart[food.id]['num']);
        }
    })
    $(this).hide()
    $(this).next('.cart_button').show()
    $(this).next('.cart_button').children('.cart_num').show().text('1')
    totalCartInfo(cart)
})
$(document).on('click', '.food-detail-layout .add_icon', function () {
    "use strict"
    // var button_box = parseInt($(this).parents('.food-item').attr('data-id'));
    // console.log($(this).parents('.food-item').attr('data-id'))
    // $('.food-list .food-item[data-id="' + food_id + '"] .add_icon').trigger('click');
    var button_box = $(this).parents('.cart_button');
    // console.log($(this).parents('.cart_button'))
    var _food_attr = getFoodInfo(button_box);
    var food        = _food_attr.food,
        cart_num    = _food_attr.cart_num,
        reduce_icon = _food_attr.reduce_icon;
    goodsType(food.type)
    if (type){
        return
    }
    if (cart[food.id]) {
        cart[food.id]['num']++;
        cart_num.text(cart[food.id]['num']);
    } else {
        cart[food.id] = {
            'num': 1,
            'id': food.id,
            'name': food.name,
            'price': food.price,
            'promotion_price': food.promotion_price,
            'discount_type': food.discount_type,
            'discount_price': food.discount_price,
            'category_id': food.category_id,
            'group_category_id': food.group_category_id || '',
            'discount_num': 0
        };
        // reduce_icon.show();
        // cart_num.show().text('1');
    }
    $.each($('.food-item'),function (index,item) {
        // console.log($(this).data('id'))
        // console.log(_food_attr.food_id,$(this).data('id'))
        if (_food_attr.food_id == $(this).data('id')){
            // console.log($(this).find('.cart_num'))
            $(this).find('.cart_num').show().text(cart[food.id]['num'])
            $(this).find('.reduce_icon').show()
            // cart_num.text(cart[food.id]['num']);
        }
    })
    totalCartInfo(cart)
});

$(document).on('click', '.food-detail-layout .reduce_icon', function () {
    "use strict"
    var button_box = $(this).parents('.cart_button');
    var _food_attr = getFoodInfo(button_box);
    var food        = _food_attr.food,
        cart_num    = _food_attr.cart_num,
        reduce_icon = _food_attr.reduce_icon;
    if (cart[food.id]['num'] > 1 && cart) {
        cart[food.id]['num']--;
        cart_num.text(cart[food.id]['num']);
    } else {
        delete cart[food.id];
        $('.cart_one').show()
        $(this).parents('.cart_button').hide()
    }
    $.each($('.food-item'),function (index,item) {
        // console.log($(this).data('id'))
        // console.log(_food_attr.food_id,$(this).data('id'))
        if (_food_attr.food_id == $(this).data('id')){
            // console.log($(this).find('.cart_num'))
            if (cart[food.id]){
                $(this).find('.cart_num').text(cart[food.id]['num'])
            }else {
                delete cart[food.id];
                $(this).find('.cart_num').hide().text('0')
                $(this).find('.reduce_icon').hide()
            }
        }
    })
    userBehavior(false,food)
    totalCartInfo(cart)
});

/**
 * 关闭商品详情
 */
$('.food-detail-mask, .icon-close').click(function () {
    $('.container').css('overflow-y', 'scroll').removeClass('filter');
    document.removeEventListener('touchmove', preHandler, false);
    $('.food-detail-container').fadeOut('fast');
});

// $('.food-list').on('touchmove',function (e) {
//     $('.food-list').scroll(function () {
//         if($('.food-list').scrollTop() >= 150){
//             // $('.left').css('position','fixed');
//             // $('.classifg h3').css("position","relative")
//             // $('.right').css('margin-left',$('.left').width());
//         }else {
//             $('.classifg h3').css("position","relative")
//         };
//         //滚动到标杆位置,左侧导航加active
//         $('.classifg').each(function () {
//             var target = parseInt($(this).offset().top - $(window).scrollTop());
//             var i = $(this).index()-1;
//             if (target <= 0) {
//                 // console.log(target)
//                 $('.classifg h3').css("position","relative").eq(i).css({"position":"fixed","top":'5.622%'})
//                 $('.type-style').removeClass('food-type_list');
//                 $('.type-style').eq(i).addClass('food-type_list');
//                 $('.banner-container').show()
//             }
//         });
//     });
// })
// $(document).on('click','.type-style',function () {
//     console.log('aaaaa')
//     var index = $(this).index();
//     if(index == 0){
//         $('.classifg').eq(0).show();
//         $('.type-style').eq(0).addClass('food-type_list');
//         $('.classifg').eq(1).hide();
//         $('.type-style').eq(1).removeClass('food-type_list');
//     }else {
//         $('.classifg').eq(0).hide();
//         $('.type-style').eq(0).removeClass('food-type_list');
//         $('.classifg').eq(1).show();
//         $('.type-style').eq(1).addClass('food-type_list');
//     }
// });

/**
 * 下单
 */
// var _payFlag = true;
$('.submit-btn-red').click(function () {
    // _payFlag = false
    // order();
    localClear()
    var ordered = [];
    $.each(cart, function (i, item) {
        if (item.num > 0) {
            ordered.push({
                "id": item.id,
                "num": item.num
            });
        }
    });
    var platform = mobile.b().weixin ? 'wechat' : '';
    if (ordered.length === 0) {
        showDialog(0, 300, "请选购商品");
        return false;
    }
    $('.loding').show()
    $.ajax({
        url: configApi('/order/confirm'),
        data: {
            items:JSON.stringify(ordered),
            id:redirect.id,
            access_token:redirect.token,
            openid:params.openid,
            platform:params.platform,
        },
        dataType: 'json',
        type: "POST",
    }).done(function (res) {
        var data = res_success(res);
        console.log(data)
        if(res.success){
            console.log(data)
            window.localStorage.items = JSON.stringify(data)
            $('.loding').hide()
            window.location.href = './pay.html'
        }else {
            $('.loding').hide()
            console.log(res.message)
            showDialog(0, 300, res.message)
        }
    }).fail(function () {
        showDialog(0, 200, "服务器异常,请退出重试")
    })
});

// function order() {
//     var ordered = [];
//     var params = JSON.parse(window.localStorage.user);
//     var id = JSON.parse(decodeURIComponent(params['redirect'])).id;
//     var openid = params.openid;
//     var platform = mobile.b().weixin ? 'wechat' : '';
//     if (params['platform'] === 'alipay') {
//         console.log(params['platform'])
//         platform = 'alipay';
//     }else if(params['platform'] === 'dingTalk'){
// 	    platform = 'dingTalk';
//     }
//     if (!id) {
//         showDialog(0, 300, "没有店铺id，请重新扫码");
//         return false;
//     }
//     $.each(cart, function (i, item) {
//         if (item.num > 0) {
//             ordered.push({
//                 "id": item.id,
//                 "num": item.num
//             });
//         }
//     });
//     console.log(JSON.stringify(ordered));
//     if (ordered.length === 0) {
//         showDialog(0, 300, "请选购商品");
//         return false;
//     }
//     if (!platform) {
//         showDialog(0, 300, '您的打开方式不对');
//         return false;
//     }
//     $('.loding').show()
//     $.ajax({
//         url: configApi('/order/create'),
//         data: {
//             openid: openid || '',
//             platform: platform,
//             items: JSON.stringify(ordered),
//             id: id
//         },
//         dataType: 'json',
//         type: "POST",
//         timeout: 8000 //超时时间设置，单位毫秒
//     }).done(function (res) {
//         console.log(res)
//         $('.loding').hide()
//         alert(1)
//         var data = res_success(res);
//         if (data) {
//             var orderInfo = data.order;
//             if (platform === 'wechat') {
//                 alert(2)
//                 jsApiCall(data.wxPayParams, orderInfo);
//                 // callpay(data.wxPayParams, orderInfo);
//             } else {
//                 window.location.href = data.aliPayUrl;
//             }
//         }else{
// 	        showDialog(0, 300, res.message);
//         }
// 	    // _payFlag = true;
//     }).fail(function () {
//         showDialog(0, 300, "服务器异常,请退出重试");
//     }).always(function (XMLHttpRequest, status) { //请求完成后最终执行参数
//         if (status === 'timeout') {//超时,status还有success,error等值的情况
//             // common.showDialog(0, 300, "网络请求超时,请重试!");
//             setTimeout(function () {
//                 // common.showDialog(0, 300, "请稍候");
//             }, 2000);
//         }
//     });
// }
/**
 * 弹窗
 * top  距离顶部多少px
 * bottom   距离底部多少px
 * content  所显示的提示信息
 * */
var showDialog = function showDialog(top, bottom, content, second) {
    $('#common-dialog .context').html(content);
    if (top != '') {
        $('#common-dialog').css({'top': top});
    }
    if (bottom != '') {
        $('#common-dialog').css({'bottom': bottom});
    }
    $('#common-dialog').fadeIn();
    $('.dialog-dark').fadeIn();
    if (second) {
        setTimeout(dismissDialog, second);
    } else {
        setTimeout(dismissDialog, 2000);
    }
    function dismissDialog() {
        $('#common-dialog').fadeOut();
        $('.dialog-dark').fadeOut();
    }
};

function loadEnd() {
    $('.load-container').fadeOut(1000, function () {
        $(this).remove();
    });
}
// function jsApiCall(jsApiParameters, orderInfo) {
//         alert(6.5)
//             wx.chooseWXPay({
//                 appId: jsApiParameters.appId,
//                 timestamp: jsApiParameters.timeStamp,
//                 nonceStr: jsApiParameters.nonceStr,
//                 package: jsApiParameters.package,
//                 signType: jsApiParameters.signType,
//                 paySign: jsApiParameters.paySign,
//                 success: function (res) {
//                     alert(7)
//                     if (res.errMsg == "chooseWXPay:ok") {
//                         zhuge.track('成功支付', {
//                             '支付方式': 'wechat',
//                             '订单编号': orderInfo.order_no
//                         }, function () {
//                             // window.location.reload();
//                             window.location.href = './views/payResult.html' + '?result=0' + '&order_no=' + orderInfo.order_no + '&created=' + orderInfo.created_at;
//                         });
//                     } else {
//                         alert(res.errMsg);
//                     }
//
//                 },
//                 cancel: function (res) {
//                     // alert(res)
//                     zhuge.track('取消支付', {
//                         '支付方式': 'wechat',
//                         '订单编号': orderInfo.order_no
//                     }, function () {
//                         // window.location.reload();
//                         // window.location.href = './views/payResult.html' + '?result=1';
//                     });
//                 },
//                 fail: function (res) {
//                     // 支付失败回调函数
//                     alert('支付失败');
//                 }
//             });
//
//
//     console.log(jsApiParameters, jsApiParameters.appId);
//     WeixinJSBridge.invoke(
//         'getBrandWCPayRequest', {
//             "appId": jsApiParameters.appId,     //公众号名称，由商户传入
//             "timeStamp": jsApiParameters.timeStamp,         //时间戳，自1970年以来的秒数
//             "nonceStr": jsApiParameters.nonceStr, //随机串
//             "package": jsApiParameters.package,
//             "signType": jsApiParameters.signType,         //微信签名方式：
//             "paySign": jsApiParameters.paySign //微信签名
//         },
//         function (res) {
//             // 支付测试环境还要将测试人员的微信号在公众号平台中加入测试支付白名单,不然调不起支付密码框
//             // 返回信息get_brand_wcpay_request:ok
//             //alert(res.errMsg)
//             console.log(res);
//             if (res.err_msg == "get_brand_wcpay_request:ok") {
//                 zhuge.track('成功支付', {
//                     '支付方式': 'wechat',
//                     '订单编号': orderInfo.order_no
//                 }, function () {
//                     window.location.reload();
//                 });
//             } else {
//                 // _payFlag = true;
//                 zhuge.track('取消支付', {
//                     '支付方式': 'wechat',
//                     '订单编号': orderInfo.order_no
//                 }, function () {
//                     // window.location.href = './views/payResult.html' + '?result=1';
//                 });
//             }
//         }
//     )
// }
// function callpay(jsApiParameters, orderInfo) {
//     if (typeof WeixinJSBridge == "undefined") {
//         if (document.addEventListener) {
//             document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
//         } else if (document.attachEvent) {
//             document.attachEvent('WeixinJSBridgeReady', jsApiCall);
//             document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
//         }
//     } else {
//         jsApiCall(jsApiParameters, orderInfo);
//     }
// }

